<template>
  <div class="invitation-box store-box">
    <Form :model="storeForm" :rules="storeFormFules" :disabled="isOrder" ref="storeFormRef" label-position="top" >
      <!-- 门店叮当 -->
      <Card class="box-card" :shadow="true">
        <p slot="title" class="cardp">
          <Icon type="md-list"></Icon>
          <span>门店订单</span>
        </p>
        <Row :gutter="10">
          <Col span="6">
            <FormItem label="门店员工" prop="storeOrder.store_employee">
              <!-- <Cascader :value="storeYG" :data="storeEmployeeOptions" @on-change="storeEmployeeChange"></Cascader> -->
              <Select v-model="storeForm.storeOrder.store_employee" placeholder="门店员工" @on-change="storeEmployeeChange">
                <Option v-for="item in storeEmployeeList" :value="item.employee_name" :key="item.employee_id">{{ item.employee_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="订单类型" prop="storeOrder.order_type">
              <Select v-model="storeForm.storeOrder.order_type" placeholder="订单类型">
                <Option v-for="item in order_type_options" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </Col>
          <!-- <Col span="6">
            <FormItem label="订单时间" prop="storeOrder.order_time">
              <DatePicker clearable :value="storeForm.storeOrder.order_time" @on-change="order_time_change" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="订单时间"></DatePicker>
            </FormItem>
          </Col> -->
          <Col span="6">
            <FormItem label="到店时间" prop="storeOrder.order_time">
              <DatePicker clearable :options="disableOptions" :value="storeForm.storeOrder.order_time" @on-change="order_time_change" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="到店时间"></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="拍摄类型">
              <Select v-model="storeForm.storeOrder.type_id" placeholder="选择拍摄类型" @on-change="typeChange">
                <Option v-for="item in typeList" :value="item.type_id" :key="item.type_id">{{ item.type_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="套系/餐"> <!-- (选择且有手机才同步ERP) -->
              <Select v-model="storeForm.storeOrder.series_id" placeholder="选择套系/套餐">
                <Option v-for="item in seriesList" :value="item.series_id" :key="item.series_id">{{ item.series_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="订单金额">
              <Input v-model="storeForm.storeOrder.order_amount" icon="logo-yen" type="number" placeholder="订单金额"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="已收金额">
              <Input v-model="storeForm.storeOrder.received_amount" icon="logo-yen" type="number" placeholder="已收金额"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="订金">
              <Input v-model="storeForm.storeOrder.deposit" icon="logo-yen" type="number" placeholder="订金"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="婚期">
              <DatePicker clearable format="yyyy-MM-dd" :value="storeForm.storeOrder.wedding_date" @on-change="wedding_date_change" type="date" placeholder="婚期"></DatePicker>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="订单备注">
              <Input v-model="storeForm.storeOrder.order_note" type="textarea" :rows="1" placeholder="订单备注"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="">
              <Button type="primary" icon="ios-checkmark-circle" @click="storeOrderConfirm">门店订单确定</Button>
            </FormItem>
          </Col>
        </Row>
      </Card>
      <!-- 门店未定 -->
      <Card class="box-card" :shadow="true" v-if="!isOrder">
        <p slot="title" class="cardp">
          <Icon type="md-list"></Icon>
          <span>门店未定</span>
        </p>
        <Row :gutter="10">
          <Col span="6">
            <FormItem label="门店员工" prop="storeUndecided.store_employee">
              <Select v-model="storeForm.storeUndecided.store_employee" placeholder="门店员工">
                <Option v-for="item in storeEmployeeList" :value="item.employee_id" :key="item.employee_id">{{ item.employee_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="是否到店">
              <Input v-model="storeForm.storeUndecided.go_store" placeholder="是否到店"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="到店时间">
              <DatePicker clearable :value="storeForm.storeUndecided.order_time" @on-change="order_time_change2" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="到店时间"></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="下次预约时间">
              <DatePicker clearable :options="disableOptions" :value="storeForm.storeUndecided.next_yuyue_time" @on-change="next_yuyue_time_change" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="下次预约时间"></DatePicker>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="门店未定备注">
              <Input v-model="storeForm.storeOrder.storeUndecided_note" type="textarea" :rows="1" placeholder="门店未定备注"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="">
              <Button type="primary" icon="ios-checkmark-circle" @click="storeUndecidedConfirm">门店未定确定</Button>
            </FormItem>
          </Col>
        </Row>
      </Card>
      <!-- 客资跟踪 -->
      <Card class="box-card" :shadow="true" v-if="!isOrder">
        <p slot="title" class="cardp">
          <Icon type="md-list"></Icon>
          <span>客资跟踪</span>
        </p>
        <Row :gutter="16">
          <Col span="6">
            <FormItem label="跟踪类型" prop="trackingData.tracking_type">
              <Select v-model="storeForm.trackingData.tracking_type" clearable placeholder="跟踪类型">
                <Option v-for="item in tracking_type_options" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="下次跟踪时间">
              <DatePicker clearable :options="disableOptions" format="yyyy-MM-dd" :value="storeForm.trackingData.next_tracking_time" @on-change="next_tracking_time_change" type="date" placeholder="下次跟踪时间"></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="预算">
              <Select v-model="storeForm.trackingData.budget" clearable placeholder="预算">
                <Option v-for="item in budget_options" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="图片备注" prop="imgRemark">
              <el-upload
                action="11"
                :http-request="kzRemarksUpload"
                :limit="1"
                :file-list="attach_list"
                list-type="picture-card"
                compress="false"
                :on-exceed="handlePictureCardExceed"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                >
                <i class="el-icon-camera"></i>
              </el-upload>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="跟踪备注">
              <Input v-model="storeForm.trackingData.tracking_note" type="textarea" :rows="1" placeholder="跟踪备注"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="">
              <Button type="primary" icon="ios-checkmark-circle" @click="trackingConfirm">跟踪确定</Button>
            </FormItem>
          </Col>
        </Row>
      </Card>
      <!-- 无效流失 -->
      <Card class="box-card" :shadow="true" v-if="!isOrder">
        <p slot="title" class="cardp">
          <Icon type="md-list"></Icon>
          <span>无效流失</span>
        </p>
        <Row :gutter="16">
          <Col span="6">
            <FormItem label="无效类型">
              <Select v-model="storeForm.invalidData.invalid_type" clearable placeholder="无效类型">
                <Option value="无效客资">无效客资</Option>
                <Option value="流失客资">流失客资</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="无效流失原因">
              <Select v-model="storeForm.invalidData.invalid_reason" clearable placeholder="无效流失原因">
                <Option value="无法联系">无法联系</Option>
                <Option value="直接拒绝">直接拒绝</Option>
                <Option value="已在集团店订单">已在集团店订单</Option>
                <Option value="微信不存在，电话空号">微信不存在，电话空号</Option>
                <Option value="无意向">无意向</Option>
                <Option value="外地客人">外地客人</Option>
                <Option value="门店客资">门店客资</Option>
                <Option value="重复客资（爱人已了解）">重复客资（爱人已了解）</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="到店时间">
              <DatePicker clearable :value="storeForm.invalidData.order_time" @on-change="invalid_order_time_change" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="到店时间"></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="无效备注">
              <Input v-model="storeForm.invalidData.invalid_note" type="textarea" :rows="1" placeholder="无效备注"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="图片备注">
              <el-upload
                action="11"
                :http-request="kzRemarksUpload"
                :limit="1"
                :file-list="attach_list"
                list-type="picture-card"
                compress="false"
                :on-exceed="handlePictureCardExceed"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                >
                <i class="el-icon-camera"></i>
              </el-upload>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="">
              <Button type="primary" icon="ios-checkmark-circle" style="margin-top: 50px;" @click="invalidConfirm">无效流失确定</Button>
            </FormItem>
          </Col>
        </Row>
      </Card>
    </Form>
  </div>
</template>

<script>
  import {
    getAllType,
    getAllSeriesByTypeIdApi,
  } from "@/api/order/index";
  import {
    updateKz,
    upload_image,
    addNewOrder,
  } from "@/api/kz/index";
  // import {store_employee_options} from './options.js'
  export default {
    props: {
      storeEmployeeList: {
        type: Array,
        default: []
      },
    },
    data() {
      return {
        rowData: '',
        seriesList: [], // 所有套系
        attach_list: [],
        storeEmployeeOptions: [],
        storeYG: [],
        storeForm: {
          storeOrder: {
            store_employee:'',
            order_type:'',
            order_time:'',
            series_id:'',
            order_amount:'',
            received_amount:'',
            deposit:'',
            wedding_date:'',
            order_note:'',
            type_id: '',
            type_name: '',
          },
          // 门店未定
          storeUndecided: {
            store_employee: '',
            go_store: '',
            order_time: '',
            next_yuyue_time: '',
            storeUndecided_note: '',
          },
          // 客资跟踪
          trackingData: {
            tracking_type: '', // 跟踪类型
            next_tracking_time: '', // 下次跟踪时间
            budget: '', // 预算
            tracking_note: '', // 跟踪备注
          },
          invalidData: {
            invalid_type: '', // 无效类型
            invalid_reason: '', // 无效原因
            order_time: '', // 到店时间
            invalid_note: '', // 无效备注
          },
        },
        typeList: [], // 类型列表
        storeFormFules: {
          'storeOrder.store_employee': [
            { required: true, message: '门店员工必填' }
          ],
          'storeOrder.order_type': [
            { required: true, message: '订单类型必填' }
          ],
          'storeOrder.order_time': [
            { required: true, message: '订单时间必填' }
          ],
          'storeUndecided.store_employee': [
            { required: true, message: '门店员工必填' }
          ],
          'trackingData.tracking_type': [
            { required: true, message: '跟踪类型必填' }
          ],
        },
        order_type_options: [
          {label:'邀约订单',value:'邀约订单'},
          {label:'到店订单',value:'到店订单'},
          {label:'礼服订单',value:'礼服订单'},
          {label:'跟妆订单',value:'跟妆订单'},
          {label:'邀约后期订单',value:'邀约后期订单'},
          {label:'回头订单',value:'回头订单'},
          {label:'在线订单',value:'在线订单'},
        ],
        tracking_type_options: [
          {label:'1日再跟踪',value:'5'},
          {label:'2日再跟踪',value:'6'},
          {label:'3日再跟踪',value:'7'},
          {label:'1周再跟踪',value:'8'},
          {label:'2周再跟踪',value:'9'},
          {label:'1月再跟踪',value:'10'},
          {label:'2月再跟踪',value:'11'},
        ],
        budget_options: [
          {label:'2k以下',value:'2k以下'},
          {label:'4k',value:'4k'},
          {label:'6k',value:'6k'},
          {label:'6k-8k',value:'6k-8k'},
          {label:'8k-10k',value:'8k-10k'},
          {label:'10k以上',value:'10k以上'},
          {label:'其他',value:'其他'}
        ],
        isOrder: false,
        disableOptions: {
          disabledDate (date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
      }
    },
    watch: {
      '$store.state.layout.app.rowData'(newValue, oldValue) {
        this.rowData = newValue
        for(let key in this.rowData) {
          if (this.rowData[key] == null || this.rowData[key] == "null") {
            this.rowData[key] = ""
          }
          if (this.rowData['kz_status_id'] == 5 || this.rowData['state_id'] == 1) {
            this.isOrder = true
          } else {
            this.isOrder = false
          }
        }
        this.$refs['storeFormRef'].resetFields()
        for (let key in this.storeForm.orderData) {
          this.storeForm.orderData[key] = this.rowData[key]
          /* if (key == 'store_employee') {
            this.storeYG = this.rowData[key].split('/')
            this.storeForm.storeOrder.store_employee = this.rowData[key].split('/')
          } */
        }
        for (let key in this.storeForm.storeUndecided) {
          this.storeForm.storeUndecided[key] = this.rowData[key]
        }

        for (let key in this.storeForm.trackingData) {
          this.storeForm.trackingData[key] = this.rowData[key]
        }
        for (let key in this.storeForm.invalidData) {
          this.storeForm.invalidData[key] = this.rowData[key]
        }
      }
    },
    created() {
      this.rowData = this.$store.state.layout.app.rowData
      if (this.rowData['kz_status_id'] == 5  || this.rowData['state_id'] == 1) {
        this.isOrder = true
      } else {
        this.isOrder = false
      }
      for (let key in this.storeForm.trackingData) {
        this.storeForm.trackingData[key] = this.rowData[key]
      }
      for (let key in this.storeForm.storeUndecided) {
        this.storeForm.storeUndecided[key] = this.rowData[key]
      }
      for (let key in this.storeForm.orderData) {
        this.storeForm.orderData[key] = this.rowData[key]
        /* if (key == 'store_employee') {
          this.storeYG = this.rowData[key].split('/')
        } */
      }
      for (let key in this.storeForm.invalidData) {
        this.storeForm.invalidData[key] = this.rowData[key]
      }

      if (this.$store.state.layout.app.typeList) {
        this.typeList = this.$store.state.layout.app.typeList
        this.storeForm.storeOrder.type_id = this.typeList[0] && this.typeList[0].type_id
      }
      this.typeList[0] && this.getAllSeries()
      console.log('mendian页面');
      // this.storeEmployeeOptions = this.storeEmployeeList;
    },
    methods: {
      // 根据拍摄类型得到所有的系列（套系）
      getAllSeries() {
        getAllSeriesByTypeIdApi({
          type_id: this.storeForm.storeOrder.type_id
        }).then(res => {
          console.log('根据拍摄类型得到所有的系列（套系）', res);
          if (res.rstpCode === '0000') {
            this.seriesList = res.data;
          } else {
            this.$Message.error(res.rstpMsg);
          }
        })
      },
      // 选择拍摄类型事件
      typeChange(e) {
        this.storeForm.storeOrder.series_id = ''
        this.getAllSeries()
        this.storeForm.storeOrder.type_name = this.typeList.find(item => item.type_id == e).type_name
      },
      // 选择订单时间
      order_time_change(val,date) {
        console.log(val);
        this.storeForm.storeOrder.order_time = val
      },
      // 选择订单时间
      order_time_change2(val,date) {
        console.log(val);
        this.storeForm.storeUndecided.order_time = val
      },
      // 选择订单时间
      invalid_order_time_change(val,date) {
        console.log(val);
        this.storeForm.invalidData.order_time = val
      },
      // 选择邀约订单婚期
      wedding_date_change(val,date) {
        console.log(val);
        this.storeForm.storeOrder.wedding_date = val
      },
      // 选择邀约订单婚期
      next_yuyue_time_change(val,date) {
        console.log(val);
        this.storeForm.storeUndecided.next_yuyue_time = val
      },
      // 选择下次跟踪时间
      next_tracking_time_change(val,date) {
        console.log(val);
        this.storeForm.trackingData.next_tracking_time = val
      },
      // 上传客资备注图片
      kzRemarksUpload(file) {
        console.log(file);
        const isLt2M = file.file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
        	this.loading = false;
        	this.$message.error("上传图片大小不能超过 2MB!");
        	return false;
        }
        const formData = new FormData();
        formData.append("image", file.file);
        upload_image(formData).then(res => {
          console.log('上传图片', res);
          if (res.rstpCode === '0000') {
            this.rowData.image_note = process.env.VUE_APP_BASE_SERVE + res.data[0].url
          }
        })
      },
      handlePictureCardExceed(files, fileList) {
         this.$Message.error('最多上传一张图片');
      },
      handlePictureCardPreview(file) {
        this.imgDialogVisible2 = true
      },
      handleRemove(file, fileList) {
        this.rowData.image_note = ''
      },
      // 门店订单确定新增到订单列表
      storeAddOrder(data) {
        addNewOrder(data).then(res => {
          console.log('门店订单确定新增到订单列表', res);
          if (res.rstpCode === '0000') {
            this.$Message.success('门店订单确定成功');
          } else {
            this.$Message.error({
              message: res.rstpMsg,
              duration: 0,
              customClass: 'myMessageClass'
            });
          }
        })
      },
      // 门店订单确定
      storeOrderConfirm() {
        let fieldsToValidate = ['storeOrder.store_employee', 'storeOrder.order_type', 'storeOrder.order_time'];
         let _self = this;
         Promise.all(fieldsToValidate.map(item => {
           let p = new Promise(function (resolve, reject) {
             _self.$refs['storeFormRef'].validateField(item, (error) => {
               resolve(error)
             })
           });
           return p;
         })).then((data) => {
           console.info(data)
           // data 里是各个字段的验证错误信息, 如果为空串则认为验证通过, 如果数组里全为空串则所有验证通过
           // 判断data 里是否全是空串
           // 去除数组空值
           data = data.filter(item => item)
           if(!data.length){
             console.log('通过验证')
             this.storeForm.storeOrder.kz_id = this.rowData.kz_id
             this.storeForm.storeOrder.sub_kz_status_id = '15'
             this.updatekezi(this.storeForm.storeOrder)
             console.log(this.seriesList.find(item => item.series_id == this.storeForm.storeOrder.series_id));
             const storeData = {
               remarks: this.storeForm.storeOrder.order_note,
               kz_name: this.rowData.kz_name,
               order_price: this.storeForm.storeOrder.order_amount,
               series_name: this.seriesList.find(item => item.series_id == this.storeForm.storeOrder.series_id).series_name,
               ...this.storeForm.storeOrder
             }
             this.storeAddOrder(storeData)
           } else {
             console.log('验证不通过')
           }
         })
      },
      // 门店未定订单确定
      storeUndecidedConfirm() {
        this.$refs['storeFormRef'].validateField('storeUndecided.store_employee', (errorMessage) => {
          console.log(errorMessage);
          if (!errorMessage) {
            this.storeForm.storeUndecided.kz_id = this.rowData.kz_id
            this.storeForm.storeUndecided.image_note = this.rowData.image_note
            this.storeForm.storeUndecided.sub_kz_status_id = '22'
            this.updatekezi(this.storeForm.storeUndecided)
          }
        });
      },
      // 跟踪确定
      trackingConfirm() {
        this.$refs['storeFormRef'].validateField('trackingData.tracking_type', (errorMessage) => {
          console.log(errorMessage);
          if (!errorMessage) {
            this.storeForm.trackingData.kz_id = this.rowData.kz_id
            this.storeForm.trackingData.image_note = this.rowData.image_note
            this.storeForm.trackingData.sub_kz_status_id = this.storeForm.trackingData.tracking_type
            this.updatekezi(this.storeForm.trackingData)
          }
        });
      },
      // 无效流失确定
      invalidConfirm() {
        this.storeForm.invalidData.kz_id = this.rowData.kz_id
        this.storeForm.invalidData.sub_kz_status_id = '21'
        this.storeForm.invalidData.image_note = this.rowData.image_note
        this.updatekezi(this.storeForm.invalidData)
      },
      // 跟新客资
      updatekezi(data) {
        updateKz(data).then(res => {
          console.log('保存编辑内容', res);
          if (res.rstpCode === '0000') {
            this.$Message.success('修改成功');
            this.$emit('queryALlKz')
          } else {
            this.$Message.error({
              message: res.rstpMsg,
              duration: 0,
              customClass: 'myMessageClass'
            });
          }
        })
      },
      // 门店员工选择
      storeEmployeeChange(value) {
        console.log(value);
        this.storeForm.storeOrder.store_employee = value
      }
    },
  }
</script>

<style scoped>

</style>
